package com.epam.dao.h2;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.epam.dao.StudentDao;
import com.epam.database.ConnectionPool;
import com.epam.entity.Student;

import com.epam.entity.User;

public class H2StudentDao extends H2AbstractEntityDao<Student> implements StudentDao<Student> {
	private static Logger LOGGER = LoggerFactory.getLogger(H2StudentDao.class);
	
	private final static String SELECT_BY_USER_ID = "SELECT s.student_id, "
			+ "p.person_name, p.person_iin, p.person_address, "
			+ "p.person_dateofbirth, p.person_phone, g.group_name"
			+ " FROM users as u inner join persons as p on u.user_id = p.person_id"
			+" INNER JOIN students as s on p.person_id = s.person_id"
			+ " INNER JOIN groups AS g on s.group_id = g.group_id"
			+ " WHERE u.user_id=?";
		

		
	@Override
	public Student selectByUserId(User user) {
		H2TrainingDao trainingDao = new H2TrainingDao();
		Student student = null;
		Connection conn = null;
		PreparedStatement pst = null;
		ResultSet rs = null;
		try {
			conn = ConnectionPool.getInstance().takeConnection();
			pst = conn.prepareStatement(SELECT_BY_USER_ID);			
			pst.setLong(1, user.getId());
			rs = pst.executeQuery();
			LOGGER.info(rs.toString());
			if (rs.next()) {
				student = new Student(rs.getLong("student_id"),user.getUserName(),
						user.getPassword(), user.getRole(), rs.getString("person_name"),
						rs.getString("person_iin"), rs.getString("person_address"),
						rs.getString("person_phone"), rs.getDate("person_dateofbirth"),
						rs.getString("group_name"));
				student.setCourses(trainingDao.selectForStudent(student.getId()));
			}
		} catch (Exception e) {
			LOGGER.warn("Failed to create the object- student");
		} finally {
			try {
				if (rs != null)
					rs.close();
				if (pst != null)
					pst.close();
				if (conn != null) {				
					ConnectionPool.getInstance().returnConnection(conn);
				}
			} catch (SQLException e) {
				LOGGER.error("Error  closing request SelecttudentByUserId");
			}
		}
		return student;
	}

	

}
